using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using FreeTextBoxControls;

using FAQComponents;
using FAQComponents.Objects;
using FAQComponents.API;
using Adge.UI.WebControls;

namespace Adge.Web.Faq.Admin
{
	/// <summary>
	/// Summary description for EditFAQ.
	/// </summary>
	public partial class EditFAQ : ClientSidePage
	{
		private int FAQID;

		public int CategoryID;
		private Color EditableBackgroundColor = Color.LightGray;

		protected void Page_Load(object sender, System.EventArgs e)
		{
			MonitorChanges(question);
			MonitorChanges(category);

			BypassModifiedMethod(btnCreateFAQ);

			if (!Page.IsPostBack)
			{
				FAQ f = FAQAPI.GetFAQ(FAQID);
				CategoryID = f.CategoryID;

				// Load up the applicable categories for this user
				User u = FAQContext.GetContext().LoggedOnUser;
				category.DataSource = u.Permissions;
				category.DataBind();

				question.Text = f.Question;
				ListItem li = category.Items.FindByValue(CategoryID.ToString());
				if (li != null) li.Selected = true;

				if (f.Approved)
					approved.Text = "Yes";
				else
					approved.Text = "No";

				// Set the text for the FAQParts FreeTextBoxes
				foreach (FAQPart part in parts)
				{
					FreeTextBox ftb = (FreeTextBox) FAQPartsPlaceHolder.FindControl(string.Concat("answer", part.FAQPartID));
					ftb.Text = part.Answer;
				}
			}
		}


		FAQPartCollection parts = null;
		private void LoadFreeTextBoxes()	// called from Init event
		{
			FAQID = InvariantString.ToInt32(Request.QueryString["ID"]);

			FAQ f = FAQAPI.GetFAQ(FAQID);
			parts = FAQAPI.GetFAQPartsForFAQ(FAQID, false);
			User u = FAQContext.GetContext().LoggedOnUser;
			Roles categoryRole = Roles.None;
			if (u.Permissions.FindCategory(f.CategoryID) != null)
				categoryRole = u.Permissions.FindCategory(f.CategoryID).UsersRole;

			question.ReadOnly = !(u.IsAdmin || categoryRole == Roles.FAQEditor || f.CreatedByUserID == u.UserID);
			category.Enabled = !question.ReadOnly;

			if (!question.ReadOnly)
			{
				questionBGColor.Text = "bgcolor=\"" + ColorTranslator.ToHtml(EditableBackgroundColor) + "\"";
				categoryBGColor.Text = "bgcolor=\"" + ColorTranslator.ToHtml(EditableBackgroundColor) + "\"";
			}

			foreach(FAQPart part in parts)
			{
				// == Add a Label ==
				Label header = new Label();
				header.Text = string.Concat("Part ", part.SortOrder, ": ") + string.Concat(part.CreatedByUser.Username, " | ", part.DateCreated.ToShortDateString());
				if (!u.IsAdmin && u.UserID != part.CreatedByUserID &&
								categoryRole != Roles.FAQEditor)
					header.Text += " (<i>You Cannot Edit This FAQ Part</i>)";
				header.CssClass = "header";

				// == Add the FreeTextBox ==
				FreeTextBox ftb = new FreeTextBox();
				ftb.SupportFolder = "FreeTextBox/";
				ftb.ID = string.Concat("answer", part.FAQPartID);
				ftb.ReadOnly = !u.IsAdmin && u.UserID != part.CreatedByUserID &&
								categoryRole != Roles.FAQEditor;
				
				base.MonitorChanges(ftb);

				TableRow tr = new TableRow();
				TableCell td = new TableCell();
				tr.Cells.Add(td);
				td = new TableCell();
				td.Controls.Add(header);
				td.Controls.Add(ftb);
				tr.Cells.Add(td);

				if (!ftb.ReadOnly)
				{
					tr.BackColor = EditableBackgroundColor;

					// add a delete button
					LinkButton delete = new LinkButton();
					delete.Text = "Delete FAQ Part";					
					if (parts.Count == 1)
						delete.Attributes["onclick"] = "javascript:if (!confirm('This will permanently delete this FAQ part.  Are you sure you want to do this?')) return false; else return confirm('This is the only FAQ part for this FAQ.  Deleting this FAQ part will delete the entire FAQ.  Is this what you are wanting to do?');";
					else
						delete.Attributes["onclick"] = "javascript:return confirm('This will permanently delete this FAQ part.  Are you sure you want to do this?');";
					delete.CommandArgument = part.FAQPartID.ToString();
					delete.Command += new CommandEventHandler(DeleteFAQPart);
					td.Controls.Add(new LiteralControl("<br />"));
					td.Controls.Add(delete);
				}

				FAQPartsPlaceHolder.Controls.Add(tr);
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();

			LoadFreeTextBoxes();

			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    

		}
		#endregion

		protected void btnCancel_Click(object sender, System.EventArgs e)
		{
			if (Request.QueryString["from"] != null)
				Response.Redirect(Request.QueryString["from"].ToString());
			else
				Response.Redirect("FAQAdmin.aspx");
		}

		protected void btnCreateFAQ_Click(object sender, System.EventArgs e)
		{
			if (!Page.IsValid) return;

			FAQ newFAQ = new FAQ(), oldFAQ = FAQAPI.GetFAQ(FAQID);
			User u = FAQContext.GetContext().LoggedOnUser;

			Roles categoryRole = Roles.None;
			if (u.Permissions.FindCategory(oldFAQ.CategoryID) != null)
				categoryRole = u.Permissions.FindCategory(oldFAQ.CategoryID).UsersRole;

			bool canEditFAQ = (u.IsAdmin || categoryRole == Roles.FAQEditor || oldFAQ.CreatedByUserID == u.UserID);

			newFAQ.FAQID = FAQID;
			if (canEditFAQ)
			{
				newFAQ.Question = question.Text;
				newFAQ.CategoryID = InvariantString.ToInt32(category.SelectedValue);
			}
			else
			{
				newFAQ.Question = oldFAQ.Question;
				newFAQ.CategoryID = oldFAQ.CategoryID;
			}

			foreach (FAQPart part in parts)
			{
				// only add the FAQPart if this user had permissions to edit it
				if (u.IsAdmin || u.UserID == part.CreatedByUserID || categoryRole == Roles.FAQEditor)
				{
					FAQPart fp = new FAQPart();
					FreeTextBox ftb = (FreeTextBox) FAQPartsPlaceHolder.FindControl(string.Concat("answer", part.FAQPartID));
					part.Answer = ftb.Text;
					newFAQ.FAQParts.Add(part);
				}
			}

			FAQAPI.UpdateFAQ(newFAQ);

			if (Request.QueryString["from"] != null)
				Response.Redirect(Request.QueryString["from"].ToString());
			else
				Response.Redirect("FAQAdmin.aspx");
		}

		private void DeleteFAQPart(object sender, CommandEventArgs e)
		{
			bool lastFAQPart = FAQAPI.GetFAQ(FAQID).FAQParts.Count == 1;

			// delete the FAQ part
			FAQAPI.DeleteFAQPart(InvariantString.ToInt32(e.CommandArgument.ToString()));

			if (!lastFAQPart)
				// refresh the page
				Response.Redirect(Request.RawUrl);
			else
				if (Request.QueryString["from"] != null)
					Response.Redirect(Request.QueryString["from"].ToString());
				else
					Response.Redirect("FAQAdmin.aspx");
				
		}
	}
}
